<template>
  <div class="login-container">
    <el-card class="login-card" @keyup.space.native="navigateToSpecifiedPage">
      <div class="logo">
        <img src="@/assets/logo.png" alt="logo">
        <h2>学生登录</h2>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="rules" label-width="0px" @keyup.enter.native="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
      </el-form>
      <el-link class="forgot-password" @click="forgotPassword" :underline='false'>忘记密码?</el-link>
    </el-card>
  </div>
</template>

<script>
import request from "@/utils/request";
import {setToken} from "@/utils/localStorage";
import socketService from "@/utils/socketService";

export default {
  name: 'loginPage',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { len: 8, message: '账号必须是8个字符', trigger: 'blur' },
          { pattern: /^\d{8}$/, message: '账号只能包含8个数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 10, message: '密码不能超过10个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const params = {
            username: this.loginForm.username,
            password: this.loginForm.password,
          };
          console.log(params);
          request.request({
            method: 'post',
            url: '/login',
            data: params,
          }).then(res => {
            console.log(res.data.message, res.data.status);
            if (res.data.status === 200) {
              const userId = res.data.userId; // 假设后端返回用户ID
              const token = res.data.token;
              setToken(token);
              localStorage.setItem('userId', userId); // 保存用户ID
              socketService.connect();
              socketService.login();
              this.$message({
                message: '登录成功',
                center: true,
                type: 'success',
                duration: '1500',
                offset: '80',
              });
              this.$router.push('/studentPage');
            } else if (res.data.status === 404) {
              console.log('登录失败：', res.data.message);
              this.$message({
                message: '登录失败 账号或密码错误',
                center: true,
                type: 'error',
                duration: '1500',
                offset: '80',
              });
              // 手动设置校验错误状态
              this.$refs.loginForm.clearValidate(); // 清除之前的校验状态
              this.$refs.loginForm.validateField('username'); // 触发用户名的校验
              this.$refs.loginForm.validateField('password'); // 触发密码的校验
            }
          }).catch(error => {
            if (error.response) {
              console.error('服务器响应错误:', error.response.data);
            } else if (error.request) {
              console.error('没有收到响应:', error.request);
            } else {
              console.error('请求发生错误:', error.message);
            }
          });
        } else {
          console.log('表单校验失败');
        }
      });
    },

    forgotPassword() {
      console.log('忘记密码被点击了');
      // 忘记密码的逻辑
    },
    navigateToSpecifiedPage() {
      this.$router.push('/adminLogin'); // 替换为你希望跳转的页面
    },
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo img {
  width: 120px;
  height: auto;
}

.login-button {
  width: 100%;
}

.forgot-password {
  display: block;
  text-align: right;
  margin-top: 10px;
}
</style>
